  <script>
  import {
    addDepartment, addOrganizational,
    deleteDepartment, deleteOrganizational,
    getAllOrganizationalStructure,
    getDepartmentById,
    getOrganizationalByOrgId,
    getOrganizationalStructureNameByDeptID,
    updateDepartment,
    updateOrganizational
  } from '@/api/systemAdministration/organizationalStructureManagement/organizationalStructure'

  function setNodeLevel(node, level) {
    node.level = level; // 首先设置当前节点的层级
    if (node.children) { // 如果当前节点有子节点
      node.children.forEach(child => setNodeLevel(child, level + 1)); // 递归地为子节点设置层级
    }
  }
  function setDepartmentManager(node){
    if(!node.children){
      node.children = [{label:node.manager,value:id}];
      id = id+1
    }else{
      node.children.forEach(child => setDepartmentManager(child));
    }
  }
  // 定义转换函数
  function transformData(node) {
      if(node.departments){
          node.value = id, // 使用后端数据中的id作为value
          node.label= node.orgName // 使用后端数据中的name作为label
      }else{
        node.value = id, // 使用后端数据中的id作为value
          node.label= node.deptName // 使用后端数据中的name作为label
      }
      id = id+1
      // 如果有子级数据，递归转换
      if (node.departments && node.departments.length) {
        node.children = node.departments
        node.children.forEach(child => transformData(child));
      }
}
let treeFirstId;
let id = 1;
let treeSecondId;
let departmentFunctionLogo;
let organizationFunctionLogo;
  export default {
    name: "index",
    data() {
      var validatePhone = (rule, value, callback) => {
        let rules = /^\d{3}-\d{8}/; // 匹配三个数字，一个连字符，后面跟着任意数量的数字
        if (rules.test(value)){
          callback();
        } else {
          callback('按规则输入数字 比如：XXX-XXXXX');
        }
      }
      var validateMobilePhone = (rule, value, callback) => {
        let rules = /^1[3-9]\d{9}$/; // 匹配三个数字，一个连字符，后面跟着任意数量的数字
        if (rules.test(value)){
          callback();
        } else {
          callback('请输入11位有效号码');
        }
      }
      return {
        //组织结构和部门的窗口
        popoverVisible: {
          //组织结构
          firstLevel: false,
          //部门
          secondLevel: false
        },
        //部门form显示
        departmentFormShow:false,
        //组织结构form显示
        organizationFormShow:false,
        //部门负责人弹窗
        visibleVisible:false,
        //tree选中
        treeSelected:{},
        //tree数据
        treeData: [],
        //tree部门负责人数据
        treeDepartmentManager:[],
        //部门form数据
        departmentForm:{
          deptID:0,
          deptName:"",
          manager:"",
          MobilePhone:"",
          Fax:""
        },
        //部门弹出框的位置
        DepartmentPopupPosition:{},
        //组织结构form数据
        organizationForm:{
          orgId:0,
          orgName:"",
          orgShortName:"",
          SortOrder:""
        },
        //部门所属机构名
        departmentOrgName: "",
        //部门form约束
        departmentRules: {
          deptName:[
            { required: true, message: '必填', trigger: 'blur' },
            { len: true, message: "长度2-10", trigger: "blur" }
          ],
          manager:[
            { required: true, message: '必填', trigger: 'blur' }
          ],
          mobilePhone:[
            { required: true, message: '必填', trigger: 'blur' },
            { validator : validateMobilePhone , trigger: 'blur' }
          ],
          fax:[
            { required: true, message: '必填', trigger: 'blur' },
            { validator : validatePhone , trigger: 'blur' }
          ],
          phone:[
            { required: true, message: '必填', trigger: 'blur' },
            { validator : validatePhone , trigger: 'blur' }
          ],
        },
        //组织结构form约束
        organizationRules: {
          orgName:[
            { required: true, message: '必填', trigger: 'blur' },
            { len: true, message: "长度2-10", trigger: "blur" }
          ],
          orgShortName:[
            { required: true, message: '必填', trigger: 'blur' }
          ],
          sortOrder:[
            { required: true, message: '必填', trigger: 'blur' }
          ]
        }
      }
    },
    mounted() {
      //页面加载完获取树形数据
      this.getSector();
    },
    methods: {
      //获取组织结构部门树形数据
      getSector: function() {
        getAllOrganizationalStructure()
          .then((data) => {
            this.treeData = data.data;
            // 在获取树形结构数据后调用
            // 设置节点层级
            this.treeData.forEach(node =>  transformData(node));
            this.treeData.forEach(node =>  setNodeLevel(node, 1));
            console.log(this.treeData)
          }).catch((error) => {
          console.log(error);
        })
      },
      //部门负责人点击方法
      DepartmentManagerHandleNodeClick(node){
        if (node.level === 3) {
          this.departmentForm.manager = node.label;
          this.visibleVisible = !this.visibleVisible;
        }
      },
      //树形结构点击
      handleNodeClick(node,event){
        //获取点击节点数据
        this.treeSelected = node
        // 根据节点层级显示不同的弹出框，组织结构
        if (node.level === 1) {
          //如果点击叶子节点的id和上一次id是同一个,则通过弹框值visible取反来开启关闭弹框
          //这里要注意：开始第一次点击的时候，treeId没有值，则直接进入else里面的逻辑
          if(treeFirstId===node.value){
            this.popoverVisible.firstLevel=!this.popoverVisible.firstLevel// 显示隐藏 department窗口
          }else{
            //否则，显示当前弹框内容
            this.popoverVisible.firstLevel=false;// 显示 department窗口
            this.popoverVisible.firstLevel=true;// 显示 department窗口
            treeFirstId = node.value
          }
          this.popoverVisible.secondLevel = false;// 隐藏 organization窗口
        } else if (node.level === 2) { //部门
          //如果点击叶子节点的id和上一次id是同一个,则通过弹框值visible取反来开启关闭弹框
          //这里要注意：开始第一次点击的时候，treeId没有值，则直接进入else里面的逻辑
          if(treeSecondId===node.value){
            this.popoverVisible.secondLevel=!this.popoverVisible.secondLevel
          }else{
            //否则，显示当前弹框内容
            this.popoverVisible.secondLevel=false;
            this.popoverVisible.secondLevel=true;
            treeSecondId = node.value
          }
          this.popoverVisible.firstLevel = false;
        }
      },
      //部门树形弹窗点击修改的方法初始化数据
      updateDepartment(){
        this.$refs.departmentRules.clearValidate()
        departmentFunctionLogo = "update"
        this.organizationFormShow = false; //避免显示两个form
        this.departmentFormShow = true; //显示部门form
        this.popoverVisible.secondLevel = !this.popoverVisible.secondLevel; //关闭部门弹窗
        getDepartmentById(this.treeSelected.deptID)
          .then((data) => {
            this.departmentForm = data.data
          })
          .catch((error) => {
            console.log(error);
          })
        getOrganizationalStructureNameByDeptID(this.treeSelected.deptID,null)
          .then((data) => {
              this.departmentOrgName = data.data.orgName;
          })
          .catch((error) => {
            console.log(error);
          })
      },
      //组织结构树形弹窗点击修改的方法初始化数据
      updateOrganization(){
        this.$refs.organizationFormRef.clearValidate()
        organizationFunctionLogo = "update";
        this.departmentFormShow = false; //避免显示两个form，
        this.organizationFormShow = true;// 显示组织结构form
        this.popoverVisible.firstLevel = !this.popoverVisible.firstLevel; //关闭组织结构弹窗
        getOrganizationalByOrgId(this.treeSelected.orgID)
          .then((data) =>{
            this.organizationForm = data.data;
          })
          .catch((error) =>{
            console.log(error);
          })
      },
      //组织结构树形弹窗点击新增的方法
      addDepartment(){
        this.$refs.departmentRules.clearValidate()
        departmentFunctionLogo = "add";
        this.organizationFormShow = false// 避免显示两个form
        this.departmentFormShow = true;// 显示部门form
        this.departmentForm = {};
        this.popoverVisible.firstLevel = !this.popoverVisible.firstLevel; //关闭组织结构弹窗
        getOrganizationalStructureNameByDeptID(null,this.treeSelected.orgID)
          .then((data) => {
            this.departmentOrgName = data.data.orgName;
          })
          .catch((error) => {
            console.log(error);
          })
      },
      //添加组织结构方法
      addOrganization(){
        this.$refs.organizationFormRef.clearValidate()
        organizationFunctionLogo = "add";
        this.organizationFormShow = true;// 显示组织结构form
        this.departmentFormShow = false;// 不显示部门form避免出现两个form标签
        this.organizationForm = {};
      },
      //部门负责人点击方法
      headOfDepartment(){
        this.visibleVisible = !this.visibleVisible;
        this.treeDepartmentManager = this.treeData;
        this.treeDepartmentManager.forEach(node => setDepartmentManager(node));
        this.treeDepartmentManager.forEach(node => setNodeLevel(node, 1));
        console.log(this.treeDepartmentManager)
      },
      //修改和新增部门信息
      DepartmentOnSubmit(){
        this.$refs.departmentRules.validate((valid) => {
          if(!valid) {
            this.$message.warning('兄嘚按规矩办事！！')
            return false
          }else {
            if (departmentFunctionLogo === "update") {
              updateDepartment(this.departmentForm)
                .then((data) => {
                  if (data.code === 200) {
                    this.$message({
                      message: '修改成功！！',
                      type: 'success'
                    });
                    this.departmentFormShow = !this.departmentFormShow;
                    this.getSector();
                  } else {
                    this.$message.error('修改失败!!');
                  }
                })
                .catch((error) => {
                  console.log(error);
                });
            } else if (departmentFunctionLogo === "add") {
              addDepartment(this.departmentForm,this.treeSelected.orgID)
                .then((data) => {
                  if (data.code === 200) {
                    this.$message({
                      message: '新增成功！！',
                      type: 'success'
                    });
                    this.departmentFormShow = !this.departmentFormShow;
                    this.getSector();
                  } else {
                    this.$message.error('新增失败!!');
                  }
                })
                .catch((error) => {
                  console.log(error);
                });
            }
          }
        })
      },
      //修改和新增组织结构信息
      organizationOnSubmit(){
        this.$refs.organizationFormRef.validate((valid) => {
          if(!valid) {
            this.$message.warning('兄嘚按规矩办事！！')
            return false;
          }else{
            if(organizationFunctionLogo === "update"){
              updateOrganizational(this.organizationForm)
                .then((data) => {
                  if(data.code === 200){
                    this.$message({
                      message: '修改成功！！',
                      type: 'success'
                    });
                    this.organizationFormShow = !this.organizationFormShow;
                    this.getSector();
                  }else{
                    this.$message.error('修改失败！！');
                  }
                })
                .catch((error) => {
                  console.log(error);
                });
            }else if(organizationFunctionLogo === "add"){
              addOrganizational(this.organizationForm)
                .then((data) => {
                  if(data.code === 200){
                    this.$message({
                      message: '新增成功！！',
                      type: 'success'
                    });
                    this.organizationFormShow = !this.organizationFormShow;
                    this.getSector();
                  }else{
                    this.$message.error('新增失败！！');
                  }
                })
                .catch((error) => {
                  console.log(error);
                });
            }
          }
        })
      },
      //删除部门信息
      deleteDepartment(){
        this.$confirm('此操作将永久删除该部门, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          deleteDepartment(this.treeSelected.deptID)
            .then((data) =>{
              if(data.code === 200){
                this.$message({
                  type: 'success',
                  message: '删除成功!'
                });
                this.popoverVisible.secondLevel = !this.popoverVisible.secondLevel
                this.getSector();
              }
            })
            .catch((error) =>{
              console.log(error);
            })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
        this.visibleDepartment = !this.visibleDepartment; //关闭部门弹窗
      },
      //删除组织结构信息
      deleteOrganization(){
        this.$confirm('此操作将永久删除该组织结构信息以及下面的所有部门, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          deleteOrganizational(this.treeSelected.orgID)
            .then((data) =>{
              if(data.code === 200){
                this.$message({
                  type: 'success',
                  message: '删除成功!'
                });
                this.popoverVisible.secondLevel = !this.popoverVisible.secondLevel
                this.getSector();
              }
            })
            .catch((error) =>{
              console.log(error);
            })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
        this.visibleDepartment = !this.visibleDepartment; //关闭部门弹窗
      },
    }
  }
  </script>
  <template>
    <div>
      <button style="margin: 20px 20px 0 50px;color: #686868" @click="addOrganization">添加结构</button>
      <div style="display: flex;margin: 20px 20px 0 50px;">
        <el-tree
          ref="tree"
          :data="treeData"
          node-key="value"
          default-expand-all
          @node-click="handleNodeClick"
        />
<!--     部门弹窗   -->
        <el-popover
          ref="popover"
          v-model="popoverVisible.secondLevel"
          trigger="manual"
          placement="right"
        >
          <span>选择操作<span style="float: right" @click="popoverVisible.secondLevel = false"><i class="el-icon-close"></i></span></span>
          <div class="nodeStyle" @click="updateDepartment">修改节点</div>
          <div class="nodeStyle" @click="deleteDepartment">删除节点</div>
        </el-popover>
<!--     组织结构弹窗   -->
        <el-popover
          ref="organizationRef"
          v-model="popoverVisible.firstLevel"
          placement="right"
          trigger="manual"
        >
          <span>选择操作<span style="float: right" @click="popoverVisible.firstLevel = false"><i class="el-icon-close"></i></span></span>
          <div class="nodeStyle" @click="updateOrganization">修改节点</div>
          <div class="nodeStyle" @click="addDepartment">添加节点</div>
          <div class="nodeStyle" @click="deleteOrganization">删除节点</div>
        </el-popover>
    <!--     部门 -->
        <el-form
          v-show="departmentFormShow"
          ref="departmentRules"
          style="width: 70%;margin-left: 300px"
          :model="departmentForm"
          :rules="departmentRules"
          label-width="auto"
          status-icon
          label-position="left"
        >
          <el-form-item label="部门名称：" prop="deptName">
            <el-input v-model="departmentForm.deptName" class="inputStyle" />
          </el-form-item>
          <el-form-item label="所属机构：" prop="region">
            <span style="margin-left: 10px;color: #686868">{{this.departmentOrgName}}</span>
          </el-form-item>
          <el-form-item label="部门负责人：" prop="manager">
            <el-input v-model="departmentForm.manager" class="inputStyle" />
            <el-button style="margin-left: 10px" @click="headOfDepartment">
              选择
            </el-button>
            <el-popover
              style="position: absolute;right: 230px;top: -100px"
              v-model="visibleVisible"
              placement="right"
            >
              <template #default>
                <span>选择操作<span style="float: right" @click="visibleVisible = false"><i class="el-icon-close"></i></span></span>
                <!--        部门负责人树形-->
                <el-tree
                  ref="departmentTree"
                  :data="treeDepartmentManager"
                  node-key="value"
                  highlight-current
                  default-expand-all
                  @node-click="DepartmentManagerHandleNodeClick"
                />
              </template>
            </el-popover>
          </el-form-item>
          <el-form-item label="联系电话：" prop="phone">
            <el-input v-model="departmentForm.phone" class="inputStyle" />
          </el-form-item>
          <el-form-item label="移动电话：" prop="mobilePhone">
            <el-input v-model="departmentForm.mobilePhone" class="inputStyle" />
          </el-form-item>
          <el-form-item label="传真：" prop="fax">
            <el-input v-model="departmentForm.fax" class="inputStyle" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="DepartmentOnSubmit">
              保存
            </el-button>
            <el-button @click="departmentFormShow = false">取消</el-button>
          </el-form-item>
        </el-form>
    <!--      组织结构 -->
        <el-form
          v-show="organizationFormShow"
          ref="organizationFormRef"
          style="width: 70%;margin-left: 300px"
          :rules="organizationRules"
          :model="organizationForm"
          label-width="auto"
          status-icon
          label-position="left"
        >
          <el-form-item label="机构名称：" prop="orgName">
            <el-input v-model="organizationForm.orgName" class="inputStyle" />
          </el-form-item>
          <el-form-item label="机构简称：" prop="orgShortName">
            <el-input v-model="organizationForm.orgShortName" class="inputStyle" />
          </el-form-item>
          <el-form-item label="排序：" prop="sortOrder">
            <el-input v-model="organizationForm.sortOrder" class="inputStyle" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="organizationOnSubmit">
              保存
            </el-button>
            <el-button @click="organizationFormShow = false">取消</el-button>
          </el-form-item>
        </el-form>
      </div>
      </div>
  </template>

  <style scoped lang="scss">
  .el-dropdown-link {
    cursor: pointer;
    color: #409EFF;
  }
  .el-icon-arrow-down {
    font-size: 12px;
  }
  .inputStyle{
    width: 250px
  }
  .nodeStyle{
    cursor: pointer
  }
  </style>
